<template>
  <!-- 折线柱状混合 -->
  <div>
    <div :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt, thousands, toolboxFullScreen } from "@/utils/utils";
import * as echarts from "echarts";

export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String
    },
    chartData: {
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      graphType: "bar",
      colors: [],
      xData: [],
      yData: [],
      legendData: []
    };
  },
  computed: {
    ...mapState(["curChartConfig"])
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function () {
        this.getCurChartConfig();
      }
    },
    chartData() {
      if (Object.keys(this.chartData).length <= 0) {
        if (this.chart) this.chart.clear();
      } else {
        this.getCurChartConfig();
      }
    }
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.$emit("domRef", document.getElementById(this.chartId))
    this.getCurChartConfig();
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach(v => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        }
        this.graphType = graphType;
      }
      if (Object.keys(this.chartData).length > 0) {
        this.init();
      }
    },
    getSeriesData() {
      let seriesData = JSON.parse(JSON.stringify(this.chartData));
      // console.log("seriesData", seriesData);
      return seriesData[0];
    },
    hexToRgba(hex, opacity) {
      let rgbaColor = "";
      let reg = /^#[\da-f]{6}$/i;
      if (reg.test(hex)) {
        rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
          "0x" + hex.slice(3, 5)
        )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
      }
      return rgbaColor;
    },

    init() {
      let seriesData = this.getSeriesData();

      // 轴线
      let xAxisLine = {
        lineStyle: {
          color:
            this.curChartConfig["axisLine"] &&
              this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].color
              : "#777",
          width: 1,
          type:
            this.curChartConfig["axisLine"] &&
              this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].type
              : "solid",
        },
      };
      // x轴分隔线
      let xSplitLine = {
        show:
          this.curChartConfig["xGridLine"] &&
          this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["xGridLine"] &&
              this.curChartConfig["xGridLine"].color) ||
            "#f0f1f3",
          type:
            this.curChartConfig["xGridLine"] &&
            this.curChartConfig["xGridLine"].type,
        },
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type,
        },
      };
      // 背景色
      let backgroundColor =
        this.curChartConfig["showBgColor"] &&
          this.curChartConfig["showBgColor"].checked
          ? this.curChartConfig["showBgColor"].color
          : "#fff";
      // 图例
      let color = [
        "#0092f6",
        "#00d4c7",
        "#aecb56",
        "#FF515A",
        "#8B5CFF",
        "#00CA69"
      ];
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // type: "shadow",
          },
          formatter: params => {
            var res = "";
            for (var i = 0; i < params.length; i++) {
              if (params[i].seriesName != "总计") {
                // 这行代码就是判断语句 具体情况 具体分析  自己打印params 来实现自己的判断
                let str_span1 = `<span >${params[i].data}</span>`
                let str_span2 = `<span >${params[i].data}</span>`
                res += `<div style="background:none">
                  ${params[i].seriesName}：
                  ${params[i].seriesName == "平均引用量" ? str_span1 : str_span2 }  
                </div>`;
              }
            }
            return res; //最后返回的数据得一个字符串 并且支持html css 显示我用的都是行内式样式 拼接成一个字符串 给最后显示 数遍悬浮的样式也是在这里设置 你的字符串是什么样式  渲染出来就是什么样的
          }
        },
        toolbox: {},
        color: color,
        grid: {
          top: "50px",
          right: "20px",
          left: "30px",
          bottom: "20px",
          containLabel: true,
        },
        legend: {
          show: this.curChartConfig["showLegend"],
          x: "center",
          y: "0",
          icon: "stack",
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            color: "#1bb4f6"
          },
          data: ["论文量", "学者数", "平均引用量"]
        },
        backgroundColor,
        xAxis: [{
          type: "category",
          data: seriesData.xData,
          boundaryGap: true,
          // axisPointer: {
          //   type: "shadow"
          // },
          axisLabel: {
            rotate: 40,
            interval: 0,
            margin: 10,
            textStyle: {
              color: "#666666",
            },
            formatter: (label) => {
              return spaceTxt(label, 20);
            },
          },
          splitLine: xSplitLine,
        },],
        yAxis: [
          {
            type: "value",
            name: "论文量",
            // min: 0,
            // max: 250,
            // interval: 50,
            axisLabel: {
              formatter: "{value}"
            },
            // 分隔线
            splitLine: ySplitLine,
          },
          {
            type: "value",
            name: "平均引用量",
            // min: 0,
            // max: 25,
            // interval: 5,
            axisLabel: {
              formatter: "{value} "
            },
            // 分隔线
            splitLine: ySplitLine,
          }
        ],
        series: [
          {
            name: "论文量",
            stack: "sum",
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value + "";
              }
            },
            barMaxWidth: 35,
            barMinWidth: 8,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  textStyle: {
                    color: "#fff"
                  },
                  position: "inside",
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                }
              }
            },
            // barWidth: 30,
            // itemStyle: {
            //   normal: {
            //     color:
            //       this.curChartConfig.graphType === "pie1"
            //         ? this.colors[i - 1]
            //         : "#0090FF",
            //     shadowBlur: 0,
            //   },
            // },
            // itemStyle: {
            //   normal: {
            //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            //         offset: 0,
            //         color: 'rgba(0,122,255,1)' // 100% 处的颜色
            //     }, {
            //         offset: 1,
            //         color: 'rgba(255,255,255,1)' // 0% 处的颜色
            //     }], false),
            //     // barBorderRadius: [20, 20, 20, 20],
            //     shadowColor: 'rgba(0,160,221,1)',
            //     shadowBlur: 0,
            // }
            // },
            tooltip: {
              valueFormatter: function (value) {
                return value + "";
              }
            },
            data: seriesData.paperData
          },
          {
            name: "学者数",
            stack: "sum",
            type: "bar",
            barMaxWidth: 35,
            barMinWidth: 8,
            barMinHeight: 30,
            itemStyle: {
              normal: {
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  textStyle: {
                    color: "#fff"
                  },
                  position: "inside",
                  formatter: function(p) {
                    return p.value > 0 ? thousands(p.value || 0) : "";
                  }
                }
              }
            },
            // barWidth: 30,
            // itemStyle: {
            //   normal: {
            //     color:
            //       this.curChartConfig.graphType === "pie1"
            //         ? this.colors[i - 1]
            //         : "#00d5f5",
            //     shadowBlur: 0,
            //   },
            // },
            // itemStyle: {
            //   normal: {
            //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            //       offset: 0,
            //       color: this.hexToRgba(color[1], 1), // 100% 处的颜色
            //     }, {
            //       offset: 1,
            //       color: this.hexToRgba(color[1], 0.1), // 0% 处的颜色
            //     }], false),
            //     shadowColor: this.hexToRgba(color[1], 0.1),
            //     shadowBlur: 0,
            //   }
            // },
            tooltip: {
              valueFormatter: function (value) {
                return value + "";
              }
            },
            data: seriesData.expertData
          },
          {
            name: "平均引用量",
            type: "line",
            tooltip: {
              valueFormatter: function (value) {
                return value + "";
              }
            },
            symbol: "circle",
            symbolSize: 8,
            smooth: false,
            yAxisIndex: 1,
            itemStyle: {
              normal: {
                // color: "#0eddfd",
                color: "#e7ae13",
                label: {
                  show: this.curChartConfig["showLabel"] || false,
                  fontSize: this.curChartConfig["fontSize"] || 12,
                  position: "top",
                  formatter: "{c}",
                  borderWidth: 10,
                  // color: "#0eddfd",
                  color: "#e7ae13",
                  padding: 4
                },
                labelLine: {
                  show: false
                }
              }
            },
            // lineStyle: {
            //   normal: {
            //     color: "#f5b72d",

            //   },
            // },
            data: seriesData.avgData,
            // smooth: true
          }
        ]
      };

      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 点击进行对比分析
      this.chart.off("click");
      this.chart.on("click", params => {
        let dataIndex = params.dataIndex;
        let op = this.chart.getOption();
        op.series[0].data.forEach((v, i) => {
          if (i == dataIndex) {
            if (v.custom_selected === true) {
              v.itemStyle.color = v.custom_color;
            } else {
              v.itemStyle.color = "red";
            }
            v.custom_selected = !v.custom_selected;
          }
        });
        this.getContrastiveData(op);
        this.chart.setOption(op);
      });

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },
    getEchartImg(base) {
      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      window.echartImg = base;
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    },
    // 保存对比分析数据
    getContrastiveData(option) {
      let arr = [];
      option.series[0].data.forEach((v, i) => {
        if (v.custom_selected === true) {
          arr.push(v);
        }
      });
      this.$emit("contrastiveData", arr);
    }
  },

  destroyed() {
    this.chart.dispose();
    this.chart = null;
  }
};
</script>

<style lang="scss" scoped>
// .chart {
//   background-color: #fff;
// }
</style>
